package com.djf.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.djf.entity.Order;
import com.djf.mapper.OrderMapper;
import com.djf.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * 订单服务实现类
 * 
 * @author djf
 * @since 2024-01-20
 */
@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    private final Random random = new Random();
    private final String[] products = {"iPhone 15", "MacBook Pro", "iPad Air", "AirPods Pro", "Apple Watch", "华为P60", "小米13", "OPPO Find X6"};
    private final String[] paymentMethods = {"支付宝", "微信支付", "银行卡", "现金"};
    private final String[] addresses = {"北京市朝阳区", "上海市浦东新区", "广州市天河区", "深圳市南山区", "杭州市西湖区"};

    @Override
    @Transactional
    public Order createOrder(Order order) {
        // 生成订单号
        if (order.getOrderNo() == null || order.getOrderNo().isEmpty()) {
            order.setOrderNo(generateOrderNo());
        }
        
        // 设置创建时间
        if (order.getCreateTime() == null) {
            order.setCreateTime(LocalDateTime.now());
        }
        
        // 计算总金额
        if (order.getTotalAmount() == null && order.getProductPrice() != null && order.getQuantity() != null) {
            order.setTotalAmount(order.getProductPrice().multiply(BigDecimal.valueOf(order.getQuantity())));
        }
        
        // 设置默认状态
        if (order.getOrderStatus() == null) {
            order.setOrderStatus(Order.OrderStatus.PENDING_PAYMENT.getCode());
        }
        
        // 保存订单
        this.save(order);
        log.info("创建订单成功，订单号：{}, 分表到：order_{}", order.getOrderNo(), 
                order.getCreateTime().format(DateTimeFormatter.ofPattern("yyyyMM")));
        
        return order;
    }

    @Override
    public List<Order> getOrdersByUserId(Long userId) {
        return baseMapper.selectByUserId(userId);
    }

    @Override
    public List<Order> getOrdersByTenantId(Long tenantId) {
        return baseMapper.selectByTenantId(tenantId);
    }

    @Override
    public List<Order> getOrdersByTimeRange(LocalDateTime startTime, LocalDateTime endTime) {
        return baseMapper.selectByTimeRange(startTime, endTime);
    }

    @Override
    public List<Order> getOrdersByUserIdAndTimeRange(Long userId, LocalDateTime startTime, LocalDateTime endTime) {
        return baseMapper.selectByUserIdAndTimeRange(userId, startTime, endTime);
    }

    @Override
    public List<Order> getOrdersByTenantIdAndTimeRange(Long tenantId, LocalDateTime startTime, LocalDateTime endTime) {
        return baseMapper.selectByTenantIdAndTimeRange(tenantId, startTime, endTime);
    }

    @Override
    @Transactional
    public boolean updateOrderStatus(Long orderId, Integer orderStatus) {
        Order order = this.getById(orderId);
        if (order != null) {
            order.setOrderStatus(orderStatus);
            order.setUpdateTime(LocalDateTime.now());
            return this.updateById(order);
        }
        return false;
    }

    @Override
    public Long countOrdersByTimeRange(LocalDateTime startTime, LocalDateTime endTime) {
        return baseMapper.countByTimeRange(startTime, endTime);
    }

    @Override
    @Transactional
    public List<Order> generateTestData(int count) {
        List<Order> orders = new ArrayList<>();
        
        // 生成不同月份的测试数据
        LocalDateTime[] testTimes = {
            LocalDateTime.of(2025, 1, 15, 10, 30),
            LocalDateTime.of(2025, 2, 20, 14, 45),
            LocalDateTime.of(2025, 3, 10, 9, 15),
            LocalDateTime.of(2025, 4, 25, 16, 20),
                LocalDateTime.of(2025, 5, 25, 16, 20),
                LocalDateTime.of(2025, 6, 25, 16, 20)

        };
        
        for (int i = 0; i < count; i++) {
            Order order = new Order();
            order.setOrderNo(generateOrderNo());
            order.setTenantId((long) (random.nextInt(3) + 1)); // 租户ID: 1-3
            order.setUserId((long) (random.nextInt(100) + 1)); // 用户ID: 1-100
            
            String product = products[random.nextInt(products.length)];
            order.setProductName(product);
            
            BigDecimal price = BigDecimal.valueOf(random.nextInt(5000) + 500); // 价格: 500-5500
            order.setProductPrice(price);
            
            int quantity = random.nextInt(5) + 1; // 数量: 1-5
            order.setQuantity(quantity);
            order.setTotalAmount(price.multiply(BigDecimal.valueOf(quantity)));
            
            order.setOrderStatus(random.nextInt(5) + 1); // 状态: 1-5
            order.setPaymentMethod(paymentMethods[random.nextInt(paymentMethods.length)]);
            order.setShippingAddress(addresses[random.nextInt(addresses.length)]);
            order.setRemark("测试订单" + (i + 1));
            
            // 随机选择时间，确保数据分布到不同的表
            order.setCreateTime(testTimes[i % testTimes.length].plusMinutes(random.nextInt(1440))); // 随机加0-1440分钟
            
            this.createOrder(order);
            orders.add(order);
        }
        
        log.info("生成测试数据完成，共生成{}条订单", count);
        return orders;
    }

    /**
     * 生成订单号
     * 
     * @return 订单号
     */
    private String generateOrderNo() {
        String timestamp = String.valueOf(System.currentTimeMillis());
        String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
        return "ORD" + timestamp + uuid.toUpperCase();
    }
}